package com.xcity.pomelo.response;

import java.util.List;

import com.xcity.db.entity.Player;
import com.xcity.game.adventure.AdventureUtils;
import com.xcity.game.buildv2.BuildV2;
import com.xcity.game.buildv2.BuildV2.State;
import com.xcity.game.buildv2.BuildV2Part;
import com.xcity.pomelo.request.ViewAdventureAttackPlayerRequest;

import naga.x.net.impl.pomelo.PomeloMessage;
import naga.x.net.impl.pomelo.protocol.Message;

@PomeloMessage(type = Message.Type.RESPONSE)
public class ViewAdventureAttackPlayerResponse extends AbstractViewPlayerResponse {

	public byte type;
	public Object build;
	
	public static class Building {
		public int id;
		public String name;
		public String image;
		public int[] parts; // 各部位等级
		public Building(BuildV2 refer) {
			id = refer.getId();
			name = refer.getTemplate().getName();
			image = refer.getTemplate().getImage();
			BuildV2Part[] _parts = refer.getParts();
			parts = new int[_parts.length];
			for (int i = 0; i < _parts.length; i++) {
				parts[i] = _parts[i].getLevel();
			}
		}
	}
	
	
	public ViewAdventureAttackPlayerResponse(int serial, Player source, Player target, byte type) {
		super(serial, target);
		this.id = AdventureUtils.fakeAttackTargetId(source, target.getId());
		this.type = type;
		if (type == ViewAdventureAttackPlayerRequest.TYPE_CAPTURE) {
			BuildV2 b = findCaptureBuild(target);
			this.build = new ViewPlayerHomeResponse.Building(b);
		} else {
			BuildV2 b = target.getBuildings2().getLast();
			this.build = new Building(b);
		}
	}
	
	static BuildV2 findCaptureBuild(Player player) {
		List<BuildV2> buildings = player.getBuildings2().getBuildings();
		BuildV2 building = find(buildings, State.BUILT);
		if (building == null) {
			building = find(buildings, State.CAPTURED);
			if (building == null) {
				building = player.getBuildings2().getLast(); // !!!error
			}
		}
		return building;
	}
	
	static BuildV2 find(List<BuildV2> buildings, State state) {
		for (int i = buildings.size() - 1; i >= 0; i--) {
			BuildV2 building = buildings.get(i);
			if (building.getState() == state) {
				return building;
			}
		}
		return null;
	}

}
